﻿using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;

using SRM.Application.PageResult.IServices;
using SRM.Core.Extension;
using SRM.Core.Models;
using SRM.Core.Models.Base;
using SRM.Core.Repositories;
using SRM.Core.Utility;
using SRM.WebSite.Models;

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace SRM.WebSite.Controllers
{
    public class ReturnOrderController : Controller
    {
        private readonly IReturnOrderServer _returnOrderServer;
        private readonly IReturnOrderDtlServer _returnOrderDtlServer;
        private readonly IRepository<PurchaseOrder> _purchaseOrderRepository;
        private readonly IRepository<PurchaseOrderDetail> _purchaseOrderDtlRepository;
        private readonly IRepository<ReturnOrder> _returnOrderRepository;
        private readonly IRepository<ReturnOrderDetail> _returnOrderDetailRepository;


        public ReturnOrderController(IReturnOrderServer returnOrderServer
            , IReturnOrderDtlServer returnOrderDtlServer
            , IRepository<ReturnOrderDetail> returnOrderDetailRepository
            , IRepository<ReturnOrder> returnOrderRepository
            , IRepository<PurchaseOrder> purchaseOrderRepository, IRepository<PurchaseOrderDetail> purchaseOrderDtlRepository)
        {
            _returnOrderServer = returnOrderServer;
            _returnOrderDtlServer = returnOrderDtlServer;
            _returnOrderDetailRepository = returnOrderDetailRepository;
            _returnOrderRepository = returnOrderRepository;
            _purchaseOrderRepository = purchaseOrderRepository;
            _purchaseOrderDtlRepository = purchaseOrderDtlRepository;
        }

        public async Task<IActionResult> Index(PagerModelInput input)
        {
            var list = await _returnOrderServer.GetReturnOrderList(input);
            return View(list);
        }

        public async Task<IActionResult> ReturnOrderDtl(PagerModelInput input)
        {
            var list = await _returnOrderDtlServer.GetReturnOrderDtl(input);
            return View(list);
        }

        public async Task<IActionResult> PreviewReturn(int Id)
        {
            var list = await _returnOrderDetailRepository.GetAllListAsync(p => p.ReturnOrderId == Id);
            return View(list);
        }

        //审核操作
        public async Task<IActionResult> ReturnOrderReview()
        {
            if (ModelState.IsValid)
            {
                var action = Request.Form["action"].ToString();
                var Ids = Request.Form["Ids"].ToString();
                List<int> IdList = CompilerExt.ConverToList(Ids);
                var retunrOrderLIst = await _returnOrderRepository.GetAllListAsync(r => IdList.Contains(r.Id));
                if (retunrOrderLIst == null || retunrOrderLIst.Count == 0)
                {
                    ViewBag.ErrorMessage = $"回货ID的信息不存在，请刷新重试。";
                    return View("Error");
                }
                var executeAction = (ExecuteActionEnum)Enum.Parse(typeof(ExecuteActionEnum), action);
                ReturnOrderStateEnum? @enum = null;
                string error = "";
                switch (executeAction)
                {
                    case ExecuteActionEnum.审核:
                        retunrOrderLIst.ForEach(r =>
                        {
                            if (r.ReviewState != ReturnOrderStateEnum.未审核)
                            {
                                error = $"选择的回货单数据状态存在不为{ReturnOrderStateEnum.未审核}的订单，操作失败！";
                                return;
                            }
                            @enum = ReturnOrderStateEnum.已审核;
                        });
                        break;

                    case ExecuteActionEnum.撤销审核:
                        retunrOrderLIst.ForEach(r =>
                        {
                            if (r.ReviewState != ReturnOrderStateEnum.已审核)
                            {
                                error = $"选择的回货单数据状态存在不为{ReturnOrderStateEnum.已审核}的订单，操作失败！";
                                return;
                            }
                            @enum = ReturnOrderStateEnum.未审核;
                        });
                        break;

                    case ExecuteActionEnum.复审:
                        retunrOrderLIst.ForEach(r =>
                        {
                            if (r.ReviewState != ReturnOrderStateEnum.已审核)
                            {
                                error = $"选择的回货单数据状态存在不为{ReturnOrderStateEnum.已审核}的订单，操作失败！";
                                return;
                            }
                            @enum = ReturnOrderStateEnum.已复审;
                        });
                        break;
                    case ExecuteActionEnum.关闭:
                        @enum = ReturnOrderStateEnum.关闭;
                        break;
                }
                if (string.IsNullOrEmpty(error) && @enum.HasValue)
                {
                    for (int i = 0; i < retunrOrderLIst.Count; i++)
                    {
                        retunrOrderLIst[i].ReviewState = @enum.Value;
                        if (@enum.Value == ReturnOrderStateEnum.未审核)
                        {
                            retunrOrderLIst[i].ReviewBy = "";
                            retunrOrderLIst[i].ReviewDate = null;
                        }
                        else
                        {
                            retunrOrderLIst[i].ReviewBy = LoginUser.LoginUsers.UserName;
                            retunrOrderLIst[i].ReviewDate = DateTime.Now;
                        }
                        await _returnOrderRepository.UpdateAsync(retunrOrderLIst[i]);
                    }
                    return Json("ok:操作成功");
                }
                else
                {
                    return Json($"no:{error}");
                }
            }
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> ReturnOrderDel()
        {
            if (ModelState.IsValid)
            {
                var Ids = Request.Form["Ids"].ToString();
                List<int> IdList = CompilerExt.ConverToList(Ids);
                var retunrOrderLIst = await _returnOrderRepository.GetAllListAsync(r => IdList.Contains(r.Id));
                if (retunrOrderLIst == null || retunrOrderLIst.Count == 0)
                {
                    ViewBag.ErrorMessage = $"回货ID的信息不存在，请刷新重试。";
                    return View("Error");
                }
                for (int i = 0; i < retunrOrderLIst.Count; i++)
                {
                    var details =
                        await _returnOrderDetailRepository.GetAllListAsync(d => d.ReturnOrderId == retunrOrderLIst[i].Id);
                    for (int j = 0; j < details.Count; j++)
                    {
                        await _returnOrderDetailRepository.DeleteAsync(details[j]);
                    }

                    await _returnOrderRepository.DeleteAsync(retunrOrderLIst[i]);
                }
                return Json("ok:操作成功");
            }
            return Json($"no:删除失败，请重试！");
        }

        [HttpGet]
        public async Task<IActionResult> ReturnOrderEdit(int? Id)
        {
            ReturnOrderViewModel model = new ReturnOrderViewModel();
            int? purchaseOrderId = null;
            ViewBag.Title = "回货单新增";
            if (Id.HasValue)
            {
                ViewBag.Title = "回货单修改";

                ReturnOrder returnOrder =
                    await _returnOrderRepository.FirstOrDefaultAsync(r => r.Id == Id.Value);
                //.Include(r => r.PurchaseOrders)

                CompilerExt.AutoMapping(returnOrder, model);
                purchaseOrderId = returnOrder.PurchaseOrderId;
            }

            model.PurchaseOrderList = PurchaseOrdersDropDownList(purchaseOrderId);
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> ReturnOrderEdit(ReturnOrderViewModel input)
        {
            if (ModelState.IsValid)
            {
                bool IsEdit = input.Id > 0;
                PurchaseOrder purchaseOrder = await _purchaseOrderRepository.FirstOrDefaultAsync(p => p.Id == input.PurchaseOrderId);
                if (purchaseOrder == null)
                {
                    ViewBag.ErrorMessage = $"采购单的信息ID为{input.Id}的信息不存在，请重试。";
                    return View("Error", ViewBag.ErrorMessage);
                }
                ReturnOrder model;

                if (!IsEdit)
                    model = new ReturnOrder();
                else
                    model = await _returnOrderRepository.FirstOrDefaultAsync(r => r.Id == input.Id);

                model.ItemCode = input.ItemCode;
                model.ItemName = input.ItemName;
                model.Remark = input.Remark;
                model.ReturnOrderCount = purchaseOrder.PurchaseCount;
                model.OrderType = purchaseOrder.PurchaseOrderType.ToString();
                model.PurchaseOrderId = purchaseOrder.Id;
                model.PurchaseOrders = purchaseOrder;

                if (!IsEdit)
                {
                    model.CreateBy = User.Identity.Name;
                    model.CreateDate = DateTime.Now;
                    model.ReturnOrderNo = "R" + SecurityHelper.GeneratePassword(6).ToUpper();
                    model.ReviewBy = null;
                    model.ReviewDate = null;
                    model.ReviewState = ReturnOrderStateEnum.未审核;
                    model.SupplierId = LoginUser.LoginUsers.SupplierId;
                }

                var returnOrderDetail =
                    await _returnOrderDetailRepository.GetAllListAsync(d => d.ReturnOrderId == model.Id);

                ReturnOrder returnOrder;
                if (IsEdit)
                {
                    foreach (var item in returnOrderDetail)
                    {
                        await _returnOrderDetailRepository.DeleteAsync(item);
                    }
                    returnOrder = await _returnOrderRepository.UpdateAsync(model);
                }
                else
                {
                    returnOrder = await _returnOrderRepository.InsertAsync(model);
                }

                List<ReturnOrderDetail> returnOrderDetails =
                    await AddReturnOrderDetail(purchaseOrder.Id, returnOrder.Id);

                for (int i = 0; i < returnOrderDetails.Count; i++)
                {
                    await _returnOrderDetailRepository.InsertAsync(returnOrderDetails[i]);
                }
                return RedirectToAction(nameof(Index));
            }
            return View(input);
        }

        //组装回货明细数据
        [NonAction]
        private async Task<List<ReturnOrderDetail>> AddReturnOrderDetail(int purchaseOrderId, int returnOrderId)
        {
            List<ReturnOrderDetail> details = new List<ReturnOrderDetail>();
            var purchaseOrderDtl = await _purchaseOrderDtlRepository.GetAllListAsync(p => p.PurchaseOrderId == purchaseOrderId);
            foreach (var item in purchaseOrderDtl)
            {
                ReturnOrderDetail detail = new ReturnOrderDetail()
                {
                    ReturnOrderId = returnOrderId,
                    Code = item.Code,
                    Name = item.Name,
                    Spec = item.Spec,
                    Color = item.Color,
                    Material = item.Material,
                    Price = item.Price,
                    Currency = item.Currency,
                    NetFinallyPriceFC = item.NetFinallyPriceFC,
                    TaxRate = item.TaxRate,
                    Remark = item.Remark,
                };
                details.Add(detail);
            }
            return details;
        }

        [HttpPost]
        public async Task<JsonResult> GetReturnOrderById()
        {
            int.TryParse(Request.Form["returnOrderId"], out int returnOrderId);
            var returnOrder = await _returnOrderRepository.FirstOrDefaultAsync(p => p.Id == returnOrderId);

            returnOrder.ReviewStateString =
                Enum.GetName(typeof(ReturnOrderStateEnum), Convert.ToInt32(returnOrder.ReviewState)).ToString();

            if (returnOrder != null)
                return Json(returnOrder);
            else
                return Json(false);
        }

        [NonAction]
        private SelectListItem[] PurchaseOrdersDropDownList(int? purchaseOrderId)
        {
            var poList = _purchaseOrderRepository.GetAll();
            if (!LoginUser.LoginUsers.IsHQ)
            {
                poList = poList.Where(p => p.SupplierId == LoginUser.LoginUsers.SupplierId);
            }
            poList = poList.Where(p => p.ReviewState == PurchaseOrderStateEnum.转回货计划);

            var purchaseOrderss = poList.AsNoTracking().OrderBy(p => p.Id).ToList();

            SelectListItem[] selectList = new SelectListItem[purchaseOrderss.Count];
            for (int i = 0; i < purchaseOrderss.Count; i++)
            {
                var item = purchaseOrderss[i];
                SelectListItem select = new SelectListItem();
                select.Text = item.PurchaseOrderNo;
                select.Value = item.Id.ToString();
                if (purchaseOrderId.HasValue && item.Id == purchaseOrderId.Value)
                {
                    select.Selected = true;
                }
                selectList[i] = select;
            }
            return selectList;
        }
    }
}
